﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Xml.Linq;
using System.Xml.Serialization;
using Abp.AspNetCore.Mvc.Authorization;
using Abp.Domain.Repositories;
using Abp.UI;
using Abp.Web.Models;
using com.sf.csim.express.service;
using Magicodes.Admin.Authorization;
using Magicodes.Admin.Configuration;
using Magicodes.Admin.SFOrders;
using Magicodes.Admin.SFOrders.Dto;
using Magicodes.Admin.Web;
using Magicodes.Admin.Web.Controllers;
using Magicodes.Admin.WULINGAddresss;
using Magicodes.Admin.WULINGAddresss.Dto;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Magicodes.Admin.Web.Models;
using Castle.Core.Logging;
using Abp.Authorization;
using System.Net;
using System.Collections;
using System.IO;
using System.Text;
using System.Xml;
using Abp.AutoMapper;

namespace Admin.Host.Controllers
{
    public class SFOrderController : AdminControllerBase
    {
        private readonly ISFOrderAppService _iSFOrderAppService;
        private readonly IConfigurationRoot _configurationRoot;
        private readonly IRepository<WULINGAddress, long> _wulingRepository;
        private readonly IRepository<SFOrder, long> _sfOrderRepository;
        private readonly IRepository<SFOrderResult, long> _sfOrderResultrepository;
        private List<WULINGAddress> _wULINGAddresses;
        private readonly ILogger _logger;

        public SFOrderController(
            ISFOrderAppService sFOrderAppService,
            IRepository<WULINGAddress, long> wulingRepository,
           IRepository<SFOrder, long> sfOrderRepository, IRepository<SFOrderResult, long> sfOrderResultrepository,
           ILogger logger,
            IHostingEnvironment env)
        {
            _iSFOrderAppService = sFOrderAppService;
            _configurationRoot = env.GetAppConfiguration();
            _wulingRepository = wulingRepository;
            _sfOrderRepository = sfOrderRepository;
            _sfOrderResultrepository = sfOrderResultrepository;
            _logger = logger;

            _logger.Info("ssssssssssssssssss");
        }


        #region 打印
        /// <summary>
        /// 系统下单 导入电子表格
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AbpMvcAuthorize(AppPermissions.Pages_Reception_SystemOrder)]
        public async Task<JsonResult> ImportFromExcel()
        {
            try
            {
                var importFile = Request.Form.Files.First();

                //Check input
                if (importFile == null)
                {
                    throw new UserFriendlyException(L("File_Empty_Error"));
                }

                if (importFile.Length > 30720 * 1000) //30KB*1000
                {
                    throw new UserFriendlyException(L("File_SizeLimit_Error"));
                }

                byte[] fileBytes;
                using (var stream = importFile.OpenReadStream())
                {

                    var data = ExcelHelper.ExcelReader(stream);
                    var columns = new List<string> {
                        "ServiceStationCode",
                        "ShippingNumber",
                        "AddressCoalescing",
                        "Weight",
                        "Quantity",
                        "NumberOfCases",
                        "ExpressProductType",
                        "PaymentMethod",
                        "MonthlyCardNumber",
                        "WhetherTheValuation",
                        "DeclaredValue",
                        "WhetherComeUndone",
                        "IndustryOrientedValueAddedServices",
                        "Note1",
                        "Note2",
                        "Note3",
                    };
                    data.Tables[0].Rows.RemoveAt(0);
                    var json = Newtonsoft.Json.JsonConvert.SerializeObject(data.Tables[0]);
                    var importList = data.Tables[0].ExcelReaderToEntitys<ImportSFOrderInputDto>(columns);

                    await _iSFOrderAppService.ImportFromExcel(importList.ToList());

                    _wULINGAddresses = _wulingRepository.GetAll().ToList();

                    foreach (var item in importList)
                    {

                    }

                    Task.Factory.StartNew(async () => {
                        await Task.Delay(1000 * 5);

                        CreateSFQiaoOrder();
                    });



                    return Json(new AjaxResponse(new { code = 0, msg = "" }));
                }


            }
            catch (UserFriendlyException ex)
            {
                return Json(new AjaxResponse(new ErrorInfo(ex.Message)));
            }

        }
         
        #endregion
         

        #region 自定义方法
        private void CreateSFQiaoOrder()
        {
            try
            {
                var reqURL = _configurationRoot.GetSection("SFQiao")["CreateOrder"];
                var checkword = _configurationRoot.GetSection("SFQiao")["Checkword"];
                var clientCode = _configurationRoot.GetSection("SFQiao")["ClientCode"];
                //var  aa=  User.Identity.Name;
                var newOrders = _sfOrderRepository.GetAllList(s => s.IsNewOrder);
                System.Threading.Tasks.Parallel.ForEach(newOrders.ToList(), (t) =>
                {

                    var myReqXML = CreateOrderXML(t);

                    //Console.WriteLine("请求报文：" + myReqXML);

                    CallExpressServiceTools tools = CallExpressServiceTools.getInstance();
                    String respXml = tools.callSfExpressServiceByCSIM(reqURL, myReqXML, clientCode, checkword) + "";

                    var isOk = false;
                    //重复下单处理
                    if (respXml.Contains("重复下单"))
                    {
                        isOk = true;
                    }
                    else if (respXml.Contains("<Head>OK</Head>"))
                    {
                        isOk = true;
                    }

                    if (isOk)
                    {
                        t.IsWithSFQiaoCreateOrder = isOk;
                        t.SFQiaoCreateOrderRespXml = respXml;
                        t.SFQiaoCreateOrderTime += 1;
                        t.IsNewOrder = false;
                        _sfOrderRepository.UpdateAsync(t);

                        //返回报文 入库
                        string xml = respXml;
                        XmlDocument doc = new XmlDocument();
                        doc.LoadXml(xml);

                        string json = JsonConvert.SerializeXmlNode(doc);
                        var data = Newtonsoft.Json.JsonConvert.DeserializeObject<SFQiaoOrderCreateResultRoot>(json);


                        var entity = ObjectMapper.Map<SFOrderResult>(data?.Response?.Body?.OrderResponse?.rls_info.rls_detail);
                        if (data?.Response?.Body?.OrderResponse != null)
                        {
                            entity.OrderId = data.Response.Body.OrderResponse.orderid;
                            _sfOrderResultrepository.InsertAsync(entity);
                        }
                    }
                    else
                    {
                        t.IsWithSFQiaoCreateOrder = isOk;
                        t.SFQiaoCreateOrderRespXml = respXml;
                        t.SFQiaoCreateOrderTime += 1;
                        _sfOrderRepository.UpdateAsync(t);
                    }

                });


            }
            catch (Exception)
            {

            }
        }

        private string CreateOrderXML(SFOrder sFOrder)
        {
            var clientCode = _configurationRoot.GetSection("SFQiao")["ClientCode"];
            var checkword = _configurationRoot.GetSection("SFQiao")["Checkword"];
            var custid = _configurationRoot.GetSection("SFQiao")["Custid"];
            var express_type = "1";

            var pay_method = "1";

            var address = _wULINGAddresses.FirstOrDefault(s => s.ServiceStationCode == sFOrder?.ServiceStationCode);



            var request = new SFQiaoCreateOrderModel.Request
            {

                Body = new SFQiaoCreateOrderModel.Body
                {
                    Order = new SFQiaoCreateOrderModel.Order
                    {
                        Cargo = new SFQiaoCreateOrderModel.Cargo
                        {
                            name = sFOrder?.ContentOfConsignment,

                            amount = "1",
                            count = Convert.ToInt32(sFOrder?.Quantity) + "",
                            unit = "件",
                            weight = sFOrder?.Weight + "",
                            source_area = "CN",
                            currency = "CNY",


                        },
                        orderid = sFOrder?.Id + "",
                        j_company = _configurationRoot.GetSection("SFQiao")["j_company"],
                        j_contact = _configurationRoot.GetSection("SFQiao")["j_contact"],
                        j_tel = _configurationRoot.GetSection("SFQiao")["j_tel"],
                        j_mobile = _configurationRoot.GetSection("SFQiao")["j_mobile"],
                        j_province = _configurationRoot.GetSection("SFQiao")["j_province"],
                        j_city = _configurationRoot.GetSection("SFQiao")["j_city"],
                        j_county = _configurationRoot.GetSection("SFQiao")["j_county"],
                        j_address = _configurationRoot.GetSection("SFQiao")["j_address"],
                        d_contact = address?.Contact,
                        d_tel = address?.ContactPhoneNumber,
                        d_mobile = address?.ContactPhoneNumber,
                        d_province = address?.Province,
                        d_city = address?.City,
                        d_county = address?.District,
                        d_address = address?.ReceiverAddress,
                        express_type = "1",
                        pay_method = "1",
                        custid = custid,// sFOrder?.MonthlyCardNumber,
                        parcel_quantity = Convert.ToInt32(sFOrder?.Quantity) + "",
                        is_docall = "0",
                        //sendstarttime = "",
                        order_source = "五菱顺丰下单系统",
                        remark = sFOrder?.Note1 + " " + sFOrder?.Note2 + " " + sFOrder?.Note2
                    }
                },
                Head = clientCode,
                lang = "zh-CN",
                service = "OrderService"
            };
            var json = Newtonsoft.Json.JsonConvert.SerializeObject(request);
            XNode node = JsonConvert.DeserializeXNode(json, "Request");
            string xml1 = node.ToString();

            return xml1;
        }
        #endregion

        #region 内部类
        

        #endregion



    }

}